package com.rafaelGarcia.eLibreria.utiles;

import java.util.HashMap;
import java.util.Map;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.metadata.ClassMetadata;

import com.rafaelGarcia.eLibreria.db.GestorDB;

public class GeneradorID {

	private static GeneradorID controlador = null;	
	private static Map<String, Integer> status = new HashMap<String, Integer>();	
	
	private GeneradorID(){
		SessionFactory sF = GestorDB.getSessionFactory();
		
		Session s = sF.openSession();
		
		Map<String, ClassMetadata> m = sF.getAllClassMetadata();
		
		for(String se: m.keySet()){
			Integer index;
			Object result = s.createQuery("select max(id) from " + se).uniqueResult();
			
			if(result == null){
				index = 0;
			}
			else{
				index = (Integer) result;
			}
			
			status.put(se, index);
		}
		
		s.close();
	}
	
	private static void iniciar(){
		if (controlador == null){
			controlador = new GeneradorID();
		}
	}
	
	public static <T> Integer getId(Class<T> c){	
		iniciar();
		
		Integer i;
		
		if(!status.containsKey(c.getName())){
			i = 1;
		}
		else{
			i = status.get(c.getName());
		}
		
		return ++i;
	}
	
	public static <T> Integer getIdPP(Class<T> c){
		iniciar();
		
		Integer i = getId(c);
		
		status.put(c.getName(), i);
		
		return i;
	}
}
